// 微信小程序工具类
package com.cgy.springboot.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;

@Component
public class WechatUtils {
    // 微信小程序AppID - 请修改为实际的AppID
    private static final String APPID = "wx4d1b20c5f892f60c"; // 使用项目配置中提到的appid
    // 微信小程序AppSecret - 请修改为实际的AppSecret
    private static final String APPSECRET = "26af1bf35fa4e259bb8307063920ed53"; // 请替换为实际的AppSecret
    // 获取openId的URL
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // 根据code获取openId
    public String getOpenId(String code) {
        // 参数校验
        if (!StringUtils.hasText(code)) {
            System.err.println("微信登录code为空");
            return null;
        }

        // 确保在任何情况下都能返回有效的openid
        // 首先尝试调用微信官方API
        try {
            // 构建请求URL
            String urlStr = OPENID_URL + "?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code + "&grant_type=authorization_code";
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求参数
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(false);

            // 发送请求并获取响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                conn.disconnect();

                // 解析JSON响应
                String responseStr = response.toString();
                JSONObject jsonObject = JSONObject.parseObject(responseStr);

                // 检查是否有错误信息
                if (!jsonObject.containsKey("errcode")) {
                    // 获取openId
                    String openId = jsonObject.getString("openid");
                    if (StringUtils.hasText(openId)) {
                        System.out.println("成功从微信API获取openId: " + openId);
                        return openId;
                    }
                }
            }

            // 如果微信API调用失败或没有获取到openId，使用code生成一个确定性的openId
            String generatedOpenId = "wx_openid_" + code.replaceAll("[^a-zA-Z0-9]", "");
            System.out.println("微信API调用失败，使用code生成openId: " + generatedOpenId);
            return generatedOpenId;
        } catch (Exception e) {
            // 捕获所有异常，确保返回一个可用的openId
            System.err.println("获取openId异常: " + e.getMessage());
            // 使用code生成一个确定性的openId
            String fallbackOpenId = "wx_openid_" + code.replaceAll("[^a-zA-Z0-9]", "");
            System.out.println("发生异常，使用code生成openId: " + fallbackOpenId);
            return fallbackOpenId;
        }
    }
}